/**
 * example
 * path -> ./modules/user
 * <a-button v-if="$auth('user.add')">Button</a-button>
 * path -> ./modules/sys/user
 * <a-button v-if="$auth('sysUser.add')">Button</a-button>
 */

import { useAccountStore } from '@/stores/account'

/**
 * 验证权限
 * @param {PermissionType} perm  权限码
 * @returns {boolean} true | false
 */
export const hasPermission = (permCode) => {
  const accountStore = useAccountStore()
  const permissionList = accountStore.PERMISSION_LIST
  return permissionList.some((n) => n == permCode)
}

const vAuth = {
  mounted(el, binding) {
    const bindVal = binding.value

    if (bindVal == undefined) return

    if (!hasPermission(bindVal)) {
      el.remove()
    }
  }
}

export default {
  install(app) {
    app.config.globalProperties.$auth = hasPermission
    app.directive('auth', vAuth)
  }
}
